package com.taobao.dao;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.xml.namespace.QName;

import org.apache.axis.client.Call;
import org.apache.axis.client.Service;

import com.taobao.pojo.Config;
import com.taobao.pojo.HttpContext;

public abstract class CommonSerDao {

	private Call getCall() throws Exception {
		Service service = new Service();
		Call call = (Call) service.createCall();
		call.setTimeout(Integer.parseInt(Config.service_time_out));
		call.setTargetEndpointAddress(new java.net.URL(Config.service_url));
		call.setReturnType(org.apache.axis.encoding.XMLType.XSD_STRING);
		return call;
	}

	public Object postRequest(String methodName, Map<String, Object> params) throws Exception {
		try {
			Call call = getCall();
			call.setOperationName(new QName(Config.namespace, methodName));
			call.setSOAPActionURI(Config.namespace + methodName);
			call.addParameter("ASn", org.apache.axis.Constants.XSD_STRING, javax.xml.rpc.ParameterMode.IN);

			Set<String> keys = params.keySet();
			Object[] paramObjects = new Object[keys.size() + 1];
			paramObjects[0] = "2735e811f859e1293fb45e99ce3dbdd6";
			int i = 1;
			for (Iterator<String> iterator = keys.iterator(); iterator.hasNext();) {
				String key = (String) iterator.next();
				call.addParameter(key, org.apache.axis.Constants.XSD_STRING, javax.xml.rpc.ParameterMode.IN);
				paramObjects[i] = params.get(key);
				i++;
			}
			String xml = (String) call.invoke(paramObjects);
			return process(getHttpContext(xml));
		} catch (Exception e) {
			throw new Exception("CommonSerDao.postRequest Error " + this.getClass());
		}
	}

	public Object getRequest(String methodName) throws Exception {
		try {
			Call call = getCall();
			call.setOperationName(new QName(Config.namespace, methodName));
			call.setSOAPActionURI(Config.namespace + methodName);
			String xml = call.invoke(new Object[] {}).toString();
			return process(getHttpContext(xml));
		} catch (Exception e) {
			throw new Exception("CommonSerDao.getRequest Error " + this.getClass());
		}
	}

	public HttpContext getHttpContext(String xml) {
		HttpContext httpContext = new HttpContext();
		httpContext.setHtml(xml);
		return httpContext;
	}

	public abstract Object process(HttpContext context) throws Exception;

}
